package com.jn.mvvm.views;

import android.os.Bundle;
import android.view.View;

import androidx.appcompat.app.AppCompatActivity;
import androidx.databinding.DataBindingUtil;
import androidx.lifecycle.MutableLiveData;
import androidx.lifecycle.Observer;
import androidx.lifecycle.ViewModelProvider;

import com.jn.mvvm.R;
import com.jn.mvvm.databinding.ActivityBook2Binding;
import com.jn.mvvm.entity.Book;
import com.jn.mvvm.viewmodel.BookViewModel2;

import java.util.List;

public class BookActivity2 extends AppCompatActivity {

    private ActivityBook2Binding binding;
    private BookViewModel2 mBookViewModel;
    private ViewModelProvider mViewModelProvider;
    private MutableLiveData<List<Book>> mBookListData;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        binding = DataBindingUtil.setContentView(this, R.layout.activity_book2);
        mViewModelProvider = new ViewModelProvider(this);
        mBookViewModel = mViewModelProvider.get(BookViewModel2.class);
        mBookListData = (MutableLiveData<List<Book>>) mBookViewModel.getLiveData();
        mBookListData.observe(this, new Observer<List<Book>>() {
            @Override
            public void onChanged(List<Book> books) {
                showBookToTextView(books);
            }
        });
        Book book = new Book();
        book.setName("Android从入门到精通");
        book.setAuthor("kong");
        binding.setBookinfo(book);
        binding.setListener(new ButtonClickListener());
    }

    private void add(Book book) {
        mBookViewModel.add(book);
    }

    private void showBookToTextView(List<Book> list) {
        String detail = "";
        if (list != null) {
            detail = list.toString();
        }
        binding.tvCount.setText("数量:" + mBookViewModel.getCount() + "\n" + detail);
    }

    public class ButtonClickListener {
        public void onClick(View view) {
            int id = view.getId();
            if (id == R.id.get) {
                List<Book> list = mBookViewModel.getBookList();
                showBookToTextView(list);
            }
        }

        public void onClick(View view, Book book) {
            int id = view.getId();
            if (id == R.id.add) {
                add(book);
            }
        }
    }
}